<?php

class GalleryItemModel extends Model{
	
	public $definitions = array(
		"tables" => array("gallery", "gallery_items"),
		"joins"	 => array("gallery.id" => "gallery_items.gallery_id"),
		"join_type" => "INNER"
	);
	
	public $order = "`gallery_items`.`id`";
	public $order_direction = "DESC";
	
	function __construct(){
		parent::__construct();
	}
	
	function findItems($gallery_id) {
		$gallery = $this->find(
			"*",
			array(
				"gallery.id" => $gallery_id
			)
		);
		$gallery_f = array();
		foreach ($gallery as $k=>$v) {
			foreach ($v as $m=>$n) {
				list($table,$field) = explode("#",$m,2);
				if ($table == "gallery") {
					$gallery_f[$field] = $n;
				}else{
					$gallery_f["items_temp"][$k][$field] = $n;
				}
			}
		}
		if (isset($gallery_f["items_temp"])) {
			foreach ($gallery_f["items_temp"] as $k=>&$v) {
				$gallery_f["items"][strtolower($v["type"])."s"][] = $v;
			}
			unset($gallery_f["items_temp"]);
		}
		return $gallery_f;
	}
	public function findItem($gallery_id,$item_id) {
		$gallery = $this->findItems($gallery_id);
		if (isset($gallery["items"])) {
			$images = $gallery["items"]["images"]; $images = is_array($images) ? $images : array();
			$videos = $gallery["items"]["videos"]; $videos = is_array($videos) ? $videos : array();
			$gallery["items"] = @array_merge_recursive($images,$videos);
			foreach ($gallery["items"] as $v) {
				if ($v["id"]==$item_id) {
					return $v;
				}
			}
		}
	}
}

?>